﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Zocono.Infrastructure.Common;
using Zocono.WCS.Domain.DomainRepository;
using Zocono.WCS.Domain.EntityInfo;
using Zocono.WCS.Domain.PlcBytesObject;
using Zocono.WCS.Domain.PlcConnectPoolDomain;
using Zocono.WCS.Domain.ProcessModuleDomain;
using Zocono.WCS.Infrastructure.PlcCommon;
using Zocono.WCS.WMSApiDomain.WebApi;

namespace Zocono.WCS.Domain.EquipmentProcessDomain.PlanarGeneralMessage
{
    /// <summary>
    /// 空托盘移动暂未使用
    /// </summary>
    public class EmptyPalletMoveService : IPlanarGeneralPlcActionProcessService
    {
        private readonly ILogUtil _LogUtil;
        private readonly IPlcConnectionPool _PlcConnectionPool;
        private readonly IWorkTaskInfoRepository _WorkTaskInfoRepository;
        private readonly IPlcWriteDbInfoRepository _PlcWriteDbInfoRepository;
        private readonly IPlcConnectionStateInfoRepository _IPlcConnectionStateInfoRepository;

        public EmptyPalletMoveService(ILogUtil logUtil
           , IPlcConnectionPool plcConnectionPool
           , IWorkTaskInfoRepository workTaskInfoRepository
           , IPlcWriteDbInfoRepository plcWriteDbInfoRepository
             , IPlcConnectionStateInfoRepository plcConnectionStateInfoRepository)
        {
            _LogUtil = logUtil;
            _PlcConnectionPool = plcConnectionPool;
            _WorkTaskInfoRepository = workTaskInfoRepository;
            _PlcWriteDbInfoRepository = plcWriteDbInfoRepository;
            _IPlcConnectionStateInfoRepository = plcConnectionStateInfoRepository;
        }

        public async Task ProcessActionMessageAsync(BytesObjectBase plcActionMessage, BytesObjectBase wcsActionMessage, EquipmentDbObject planarEquipmentDbObject/*, BytesObjectBase plcStateMassge*/)
        {
            var plcMessage = plcActionMessage as PlanarGeneralPlcActionBO;//Plc的动作报文
            var wcsMessage = wcsActionMessage as PlanarGeneralWcsActionBO;//Wcs的动作报文
            //var plcStateBo = plcStateMassge as PlcOnLineStateBO;//Plc在线离线报文 没有设备信息

            PlanarGeneralWriteWcsAction writeBo = null;//写入Plc的报文
            PlcConnectionS7 plcConn = _PlcConnectionPool.S7GetWritePlcConnection(plcMessage.PlcConnectionID);//plc写入连接（不锁定）

            //1. 验证plc是否在线
            var plcIPStates = await _IPlcConnectionStateInfoRepository.GetFirstAsync(l => l.PlcConnectionID == plcMessage.PlcConnectionID && l.Connected == true);
            if (plcIPStates == null)
            {
                _LogUtil.Info($"到达DD台处理失败：设备编号{plcMessage.EquipmentCode}{plcConn.IP}plc已离线");
                return;
            }

            #region plc写入连接获取&写入报文构建
            //目标位置
            string position = string.Empty;
            //写入plc的报文配置获取
            var objectType = typeof(PlanarGeneralWriteWcsAction).Name;
            var writeConfig = await _PlcWriteDbInfoRepository.GetFirstAsync(s => s.EquipmentCode == plcMessage.EquipmentCode && s.ObjectType == objectType);
            if (writeConfig == null)
            {
                _LogUtil.Info($"人工处理口(ArriveDDService.EmptyPalletMoveService)处理失败：设备{plcMessage.EquipmentCode},获取PLC写入配置失败");
                return;
            }


            try
            {
                //查询是否空满或异常盘
                var result = await WCSMessageWithWMSApi.WMSCheckExistPalletbatteryCombineInfoAsync(plcMessage.PalletBarcode);

                if (result == 3)
                {
                    _LogUtil.Info($"人工处理口(ArriveDDService.EmptyPalletMoveService)处理失败：设备{plcMessage.EquipmentCode},获取是否空满异常");
                    return;
                }
                bool bol = result == 1 ? false : true;
                
                var model = await _PlcWriteDbInfoRepository.AsSugarClient().Queryable<FormationRouteInfo>()
                                         .Where((a) => a.EquipmentCode == plcMessage.EquipmentCode.ToString() && a.ISFull == bol)
                                         .FirstAsync();

                if (model != null)
                    position = model.ToPosition;

            }
            catch (Exception ex)
            {

                _LogUtil.Error($"人工处理口(ArriveDDService.EmptyPalletMoveService)处理失败:设备({plcMessage.EquipmentCode})查询是否空满异常：{ex.Message}");
            }


            //构建写入报文
            writeBo = new PlanarGeneralWriteWcsAction(
                writeConfig.PlcConnectionId,
                writeConfig.ID,
                writeConfig.DbCode,
                writeConfig.DbStart,
                objectType,
                writeConfig.EquipmentCode.ToInt32(),
                plcMessage.ActionType,
                position.ToInt32(),//修改
                taskCode: plcMessage.TaskCode,
                palletBarcode: plcMessage.PalletBarcode,
                plcMessage.PalletType,
                alrmCode: plcMessage.AlrmCode);


            if (plcConn == null)
            {
                _LogUtil.Info($"人工处理口(ArriveDDService.EmptyPalletMoveService)：设备编号{writeBo.EquipmentCode}获取连接({writeBo.PlcConnectionID})失败");
                return;
            }
            #endregion

            var writeBl = await plcConn.WriteDbAsync(writeBo.DbCode, writeBo.DbStart, writeBo.Deserialize());
            if (!writeBl)
            {
                _LogUtil.Info($"人工处理口(ArriveDDService.EmptyPalletMoveService)：PLC(IP{plcConn.IP},设备编号{writeBo.EquipmentCode})写入报文失败");
            }
            else
            {
                _LogUtil.Info($"人工处理口(ArriveDDService.EmptyPalletMoveService)发送报文  PLCId:{writeBo.PlcConnectionID} DBId:{writeBo.PlcWriteDbID}  设备编号{writeBo.EquipmentCode} WCS握手{writeBo.ActionType}");
            }
            return;


        }
    }
}
